package dbexp.model;

import java.util.ArrayList;
import java.util.List;

public class TableData extends Table {
	private List<List<Object>> rows = new ArrayList<List<Object>>();
	private int maxLength = 0;
	private static final long serialVersionUID = 1L;

	public TableData() {
		super();
	}

	public TableData(String tname) {
		super(tname);
	}

	public TableData(String tname, String sch) {
		super(tname, sch);
	}

	public void addData(List<Object> o) {
		if (o != null) {
			// int length = o.toString().length();
			// if(length>maxLength){
			// maxLength = length;
			// }
		}
		rows.add(o);
	}

	public List<List<Object>> getRows() {
		return rows;
	}

	public int getMaxLength() {
		return maxLength;
	}

	public String getQuery(int operation) {
		if (operation == INSERT_RECORD) {
			return getInsertQuery("");
		} else if (operation == UPDATE_RECORD) {
			return "UPDATE " + getObjectNameForQuery() + " SET";
		} else if (operation == DELETE_RECORD) {
			return "DELETE FROM TABLE " + getObjectNameForQuery() + " WHERE";
		}
		return oneFromDual();
	}

	private String getInsertQuery(String string) {
		String out = string;
		if (requiredFieldIsNotNull()) {
			List<List<Object>> rows = getRows();
			for (int row = 0; row < rows.size(); row++) {
				out += "INSERT INTO " + getObjectNameForQuery() + " VALUES(";
				List<Object> oneRow = rows.get(row);
				for (int c = 0; c < getColumns().size(); c++) {
					Object data = oneRow.get(c);
					out += ","
							+ getFormattedDataType(getColumns().get(c), data);
				}
				out = out.replaceFirst(",", "");
				out += ");";
			}
		}
		return out;
	}

	public String getFormattedDataType(Column c, Object o) {

		String typeString = c.getDataType() == null ? "" : c.getDataType();

		StringBuilder buffer = new StringBuilder();

		int _type = c.sqlType();
		if (_type == 0) {
			_type = c.getSqlType(typeString);
		}
		if (!c.isNumber(o) && !c.isCurrency(o)) {
			buffer.append("\"");
			buffer.append(o);
			buffer.append("\"");
		} else {
			buffer.append(o);
		}
		return buffer.toString();
	}
}
